package com.cardvalue.sys.mode;

import android.content.Context;
import android.text.TextUtils;
import com.alibaba.fastjson.JSON;
import com.cardvalue.sys.cache.LocalCache;
import com.cardvalue.sys.entity.Apply;
import com.cardvalue.sys.entity.Bank;
import com.cardvalue.sys.entity.Confirmlist;
import com.cardvalue.sys.entity.Coupon;
import com.cardvalue.sys.entity.Credit;
import com.cardvalue.sys.entity.FileListOnce;
import com.cardvalue.sys.entity.Industrylist;
import com.cardvalue.sys.entity.Message;
import com.cardvalue.sys.entity.PostCreateAuth;
import com.cardvalue.sys.entity.SelHasLeaseContract;
import com.cardvalue.sys.entity.Shop;
import com.cardvalue.sys.entity.User;
import com.cardvalue.sys.entity.VerifyImgCode;
import com.cardvalue.sys.newnetwork.Config;
import com.cardvalue.sys.tool.MessageBox;
import com.cardvalue.sys.tool.Utiltools;
import com.cardvalue.sys.tool.XXTEA2;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import io.realm.Realm;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import timber.log.Timber;

/**
 * 用户
 * Created by cardvalue on 2016/4/18.
 */
public class UserService {
    private Retrofit retrofit;
    private  Service.getUserInfo  getUserInfoService;//获取用户
    private Service.UpdateInfo   updateInfoService;//更新用户
    private Service.getPlanFundTerm  getPlanFundTermService;//获取融资期限的列表
    private Service.industrylist industrylistService;//查询行业清单1
    private  Service.CreateCreditLimit   creditLimitService;//创建授信
    private Service.getCreditLimit getCreditLimitService;//获取授信
    private Service.latesApplication latesApplication;//获取最新的申请
    private Service.createNewCredit  createNewCreditService;//创建申请
    private  Service.getMessage  getMessage;//获取消息
    private Service.getCoupon  getCoupon;//查询红包
    private Service.getShop  getShop;//获取商户列表
    private  Service.queryUploadFileList queryUploadFileList;//查询检查清单  获取图片
    private Service.JXLGetVerityCode jxlGetVerityCode;//聚信力验证第一步
    private Service.JXLGetJxlSubmitCode  jxlGetJxlSubmitCode;//聚信力验证第二步
    private Service.CreditReportVerifyCode  creditReportVerifyCode;//征信报告获取验证码
    private  Service.CreditReport creditReport;//征信报告验证的第二步
    private Service.confirmlist mconfirmlist;//查询确认清单  1：申请信息，2：融资方案，3：融资保理通知书
    private Service.UpdateApplication   updateApplication ;//更新申请
    private Service.CreateAuthorization CreateAuthService;//创建授权
    private Service.GetBank getBank;//查询银行清单


    private  Realm  realm;
    private Context context;
    public  UserService(Context context){
        this.context=context;
        realm = Realm.getDefaultInstance();
        OkHttpClient newClient = new OkHttpClient().newBuilder().readTimeout(20000, TimeUnit.SECONDS).build();
        retrofit = new Retrofit.Builder()   //new出对象
                .baseUrl(Config.getServerIp())  //添加url\
                .client(newClient)
                .addConverterFactory(GsonConverterFactory.create()) //利用gson解析
                .build();
    }


    /**
     * 查询银行清单
     */
    public void getBank(String where,final GetBankCallback getBankCallback){
        getBank=  retrofit.create(Service.GetBank.class);
        Call<Bank> resp=getBank.attempBank(LocalCache.getStringLocalData(context,"objectId"),
                LocalCache.getStringLocalData(context,"accessToken"),where);
        resp.enqueue(new Callback<Bank>() {
            @Override
            public void onResponse(Call<Bank> call, Response<Bank> response) {
                Bank bank=response.body();
                Utiltools.printE("=查询银行清单==",JSON.toJSONString(bank)+"=====银行=======");
                if(TextUtils.isEmpty(bank.getError())){
                    if(getBankCallback!=null){
                        getBankCallback.success(bank);
                    }
                }else{
                    MessageBox.ToastShow(bank.getError()+"",context);
                }
            }

            @Override
            public void onFailure(Call<Bank> call, Throwable t) {

            }
        });

    }






    /**
     * 创建授权
     */
     public  void  getUserCreateAuthService(PostCreateAuth task,final GetPostCreateAuthCallback PostCreateAuthCallback){
         CreateAuthService=retrofit.create(Service.CreateAuthorization.class);
         Call<PostCreateAuth>  resp=CreateAuthService.attemptCreateAuthorization(task);
         resp.enqueue(new Callback<PostCreateAuth>() {
             @Override
             public void onResponse(Call<PostCreateAuth> call, Response<PostCreateAuth> response) {
                 PostCreateAuth   postCreateAuth=response.body();
                 Utiltools.printE("创建授权applysucess====",JSON.toJSONString(postCreateAuth));
                 if(TextUtils.isEmpty(postCreateAuth.getError())){
                      if(PostCreateAuthCallback!=null){
                          PostCreateAuthCallback.success(postCreateAuth);
                      }
                 }
             }

             @Override
             public void onFailure(Call<PostCreateAuth> call, Throwable t) {

             }
         });

     }



    /**
     * 更新申请
     * updateApplication
     */
    public  void GetUpdateApplication(Apply  apply,final GetApplyCallback GetApplyCallback){
        updateApplication=retrofit.create(Service.UpdateApplication.class);
        Call<Apply>  resp=updateApplication.attemUpdateApplication(LocalCache.getStringLocalData(context,"objectId"),
                LocalCache.getStringLocalData(context,"accessToken"),LocalCache.getStringLocalData(context,"applicationId"),apply) ;
        resp.enqueue(new Callback<Apply> (){
            @Override
            public void onResponse(Call<Apply> call, Response<Apply> response) {
                Apply apply=response.body();
                Timber.e("更新申请 applysucess==="+JSON.toJSONString(apply));
                if(TextUtils.isEmpty(apply.getError())){
                    if(GetApplyCallback!=null){
                        GetApplyCallback.success(apply);
                    }
                }else {
                    MessageBox.ToastShow(apply.getError()+"",context);
                    return;
                }

            }

            @Override
            public void onFailure(Call<Apply> call, Throwable t) {

            }
        });



    }



    /**
     * 查询确认清单  1：申请信息，2：融资方案，3：融资保理通知书
     * @param type
     */
    public void confirmlist(String type,final GetConfirmlistCallback  confirmlistCallback){
        mconfirmlist=retrofit.create(Service.confirmlist.class);
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("type",type);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Call<ArrayList<Confirmlist>>  resp=mconfirmlist.attempConfirmlist(LocalCache.getStringLocalData(context,"objectId"),
                LocalCache.getStringLocalData(context,"accessToken"),LocalCache.getStringLocalData(context,"applicationId"),jsonObject.toString());
        resp.enqueue(new Callback<ArrayList<Confirmlist>>() {
            @Override
            public void onResponse(Call<ArrayList<Confirmlist>> call, Response<ArrayList<Confirmlist>> response) {
                ArrayList<Confirmlist> confirmList=response.body();
                Timber.e( JSON.toJSON(confirmList)+"=======查询确认清单========");
                Utiltools.printE("===查询确认清单==",JSON.toJSON(confirmList)+"===");
                if(confirmList.size()>0){
                    if(confirmlistCallback!=null){
                        confirmlistCallback.success(confirmList);
                    }

                }


            }

            @Override
            public void onFailure(Call<ArrayList<Confirmlist>> call, Throwable t) {

            }
        });
    }



    /**
     * 征信报告  （还没有测试通过，第二步）
     * @param name
     * @param password
     * @param verityCode
     * @param tradeCode
     * @param sessionId
     * @param getcreatVerityCodeCallback
     */
    public void CreditReport(String name,String password,String verityCode,String tradeCode,String sessionId,final GetcreatVerityCodeCallback getcreatVerityCodeCallback){
        creditReport=retrofit.create(Service.CreditReport.class);
        VerifyImgCode verifyImgCode=new VerifyImgCode();
        verifyImgCode.setUsername(name);
        verifyImgCode.setPassword(password);
        verifyImgCode.setVerityCode(verityCode);
        verifyImgCode.setTradeCode(tradeCode);
        verifyImgCode.setSessionId(sessionId);
        Map<String,String> pm = new HashMap<String,String>();
        pm.put("p", "cvbaoli-"+ XXTEA2.encryptToBase64String(new Gson().toJson(verifyImgCode), "083a8248815"));
        Call<VerifyImgCode>  res=creditReport.attempCreditReport(LocalCache.getStringLocalData(context,"objectId"),
                LocalCache.getStringLocalData(context,"accessToken"),LocalCache.getStringLocalData(context,"applicationId"),pm);
        res.enqueue(new Callback<VerifyImgCode>() {
            @Override
            public void onResponse(Call<VerifyImgCode> call, Response<VerifyImgCode> response) {
                VerifyImgCode verifyImgCode1=response.body();
                if(TextUtils.isEmpty(verifyImgCode1.getError())){
                    if(getcreatVerityCodeCallback!=null){
                        getcreatVerityCodeCallback.success(verifyImgCode1);
                    }
                }else{
                    MessageBox.ToastShow(verifyImgCode1.getError()+"",context);
                    return;
                }
            }

            @Override
            public void onFailure(Call<VerifyImgCode> call, Throwable t) {

            }
        });
    }


    /**
     * 征信报告获取验证码
     */
    public void creditReportVerifyCode(final GetcreatVerityCodeCallback getcreatVerityCodeCallback){
        creditReportVerifyCode=retrofit.create(Service.CreditReportVerifyCode.class) ;
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("type","1");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Call<VerifyImgCode>   res=creditReportVerifyCode.attemptVerifyImgCode(LocalCache.getStringLocalData(context,"objectId"),
                LocalCache.getStringLocalData(context,"accessToken"),jsonObject.toString());
        res.enqueue(new Callback<VerifyImgCode>() {
            @Override
            public void onResponse(Call<VerifyImgCode> call, Response<VerifyImgCode> response) {
                VerifyImgCode  verifyImgCod=response.body();
                Utiltools.printE("征信报告获取验证码",JSON.toJSONString(verifyImgCod)+"-----");
                if(TextUtils.isEmpty(verifyImgCod.getError())){
                    if(getcreatVerityCodeCallback!=null){
                        LocalCache.saveDataToLocal(context,"sessionId",verifyImgCod.getSessionId());
                        getcreatVerityCodeCallback.success(verifyImgCod);
                    }
                }else{
                    MessageBox.ToastShow(verifyImgCod.getError()+"",context);
                    return;
                }
            }

            @Override
            public void onFailure(Call<VerifyImgCode> call, Throwable t) {

            }
        });
    }


    /**
     * jxlGetJxlSubmitCode
     * 聚信力验证第二步
     */
    public void jxlGetJxlSubmitCode(String captcha,String mobilePhone,String password,
                                    final GetjxlGetVerityCodeCallback callback){
        jxlGetJxlSubmitCode=retrofit.create(Service.JXLGetJxlSubmitCode.class);
        User user=new User();
        user.setCaptcha(captcha);
        user.setMobilePhone(mobilePhone);
        user.setPassword(password);
        user.setWebsite(LocalCache.getStringLocalData(context,"website"));//缓存取
        user.setUserId(LocalCache.getStringLocalData(context,"objectId"));
        user.setToken( LocalCache.getStringLocalData(context,"accessToken"));

        Call<User> res=jxlGetVerityCode.attemJXLGetVerity(LocalCache.getStringLocalData(context,"objectId"),
                LocalCache.getStringLocalData(context,"accessToken"),LocalCache.getStringLocalData(context,"applicationId"),user);
        res.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                User user=response.body();
                Utiltools.printE("聚信力验证第二步",JSON.toJSONString(user).toString());
                if(callback!=null){
                    callback.success(user);
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {

            }
        });
    }


    /**
     * jxlGetVerityCode
     * 聚信力验证第一步
     */
    public  void   jxlGetVerityCode(String ownerName,String ownerSSN,String mobilePhone,String password,final GetjxlGetVerityCodeCallback callback){
        jxlGetVerityCode=retrofit.create(Service.JXLGetVerityCode.class);
        User user=new User();
        user.setOwnerName(ownerName);
        user.setOwnerSSN(ownerSSN);
        user.setMobilePhone(mobilePhone);
        user.setPassword(password);
        Call<User> res=jxlGetVerityCode.attemJXLGetVerity(LocalCache.getStringLocalData(context,"objectId"),
                LocalCache.getStringLocalData(context,"accessToken"),LocalCache.getStringLocalData(context,"applicationId"),user);
        Utiltools.printE("聚信力验证第yiyi步","------------------");
        res.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                User user=response.body();
                Utiltools.printE("聚信力验证第一步",JSON.toJSONString(user).toString()+"------------------");
                Timber.e("聚信力验证第一步"+JSON.toJSONString(user).toString()+"==========================");
                if(TextUtils.isEmpty(user.getError())){
                    if(user.getWebsite()!=null&&!user.getWebsite().equals("")){
                        LocalCache.saveDataToLocal(context,"website",user.getWebsite());
                    }
                    if(callback!=null){
                        callback.success(user);
                    }
                }else {
                    if(callback!=null){
                        callback.cancelDialog();
                    }

                    MessageBox.ToastShow(user.getError()+"",context);
                    return;
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {

            }
        });
    }

    /**
     *查询检查清单  获取图片
     */
    public void getqueryUploadFileList(final GetFileListOnceCallback getFileListOnceCallback){
        queryUploadFileList=retrofit.create(Service.queryUploadFileList.class);
        Call<FileListOnce>  res=queryUploadFileList.attemgetQueryUploadFileList(LocalCache.getStringLocalData(context,"objectId"),
                LocalCache.getStringLocalData(context,"accessToken"),LocalCache.getStringLocalData(context,"objectId"));
        res.enqueue(new Callback<FileListOnce>() {
            @Override
            public void onResponse(Call<FileListOnce> call, Response<FileListOnce> response) {
                FileListOnce fileListOnce=response.body();
                Utiltools.printE("获取图片",JSON.toJSONString(fileListOnce)+"==获取图片==");
                if(getFileListOnceCallback!=null){
                    getFileListOnceCallback.success(fileListOnce);
                }
            }

            @Override
            public void onFailure(Call<FileListOnce> call, Throwable t) {

            }
        });


    }

    /**
     * 获取商户列表
     */
    public void getShop(){
        getShop=retrofit.create(Service.getShop.class);
        Call<ArrayList<Shop>> resp=getShop.attemgetShop(LocalCache.getStringLocalData(context,"objectId"),
                LocalCache.getStringLocalData(context,"accessToken"));
        resp.enqueue(new Callback<ArrayList<Shop>>() {
            @Override
            public void onResponse(Call<ArrayList<Shop>> call, Response<ArrayList<Shop>> response) {
                ArrayList<Shop> shops=response.body();
                Utiltools.printE("获取商户列表===",JSON.toJSONString(shops)+"====");
                if(shops.size()>0){
                    realm.beginTransaction();
                    realm.copyToRealmOrUpdate(shops); //merchantId  为主键
                    realm.commitTransaction();
                }
            }

            @Override
            public void onFailure(Call<ArrayList<Shop>> call, Throwable t) {

            }
        });
    }



    /**
     * 查询红包
     */
    public  void getCoupon(){
        getCoupon=retrofit.create(Service.getCoupon.class);
        Call<ArrayList<Coupon>>  resp=getCoupon.attemgetCoupon(LocalCache.getStringLocalData(context,"objectId"),
                LocalCache.getStringLocalData(context,"accessToken"),LocalCache.getStringLocalData(context,"objectId"));
        resp.enqueue(new Callback<ArrayList<Coupon>>() {
            @Override
            public void onResponse(Call<ArrayList<Coupon>> call, Response<ArrayList<Coupon>> response) {
                ArrayList<Coupon>  coupons=response.body();
                Utiltools.printE("获取红包===",JSON.toJSONString(coupons)+"====");
                if(coupons.size()>0){
                    realm.beginTransaction();
                    realm.copyToRealmOrUpdate(coupons);//id为主键
                    realm.commitTransaction();

                }
            }

            @Override
            public void onFailure(Call<ArrayList<Coupon>> call, Throwable t) {

            }
        });
    }




    /**?where={"type":"1"}&skip=10&limit=10
     * 获取消息
     * @param callback
     */
    public  void getMessage(String type,final GetMessageCallback callback ){
        getMessage=retrofit.create(Service.getMessage.class);
        JSONObject jsonObject=new JSONObject();
        String where="";
        try {
            jsonObject.put("type",type) ;
            // where="?where="+jsonObject+"&skip="+10+"&limit="+10;
            where=jsonObject.toString()+"&skip="+10+"&limit="+10;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Call<ArrayList<Message>> resp=getMessage.attemgetMessage(LocalCache.getStringLocalData(context,"objectId"),
                LocalCache.getStringLocalData(context,"accessToken"),where);
        Utiltools.printE("where",where+"===");
        resp.enqueue(new Callback<ArrayList<Message>>() {
            @Override
            public void onResponse(Call<ArrayList<Message>> call, Response<ArrayList<Message>> response) {
                ArrayList<Message>  message=response.body();
                Utiltools.printE("获取消息：",JSON.toJSONString(message).toString()+"======");
                if(callback!=null){
                    realm.beginTransaction();
                    realm.copyToRealmOrUpdate(message);//id 作为主键
                    realm.commitTransaction();
                    callback.success(message);
                }
            }

            @Override
            public void onFailure(Call<ArrayList<Message>> call, Throwable t) {

            }
        });

    }

    /**
     * 创建申请
     * @param callback
     */
    public void  NewCreditInfo(final GetApplyCallback callback){
        createNewCreditService=retrofit.create(Service.createNewCredit.class);
        Apply apply=new Apply();
        apply.setMerchantId(Integer.parseInt(LocalCache.getStringLocalData(context,"objectId")));
        Call<Apply> resp= createNewCreditService.attemcreateNewCredit(LocalCache.getStringLocalData(context,"objectId"),
                LocalCache.getStringLocalData(context,"accessToken"),apply);
        resp.enqueue(new Callback<Apply>() {
            @Override
            public void onResponse(Call<Apply> call, Response<Apply> response) {
                Apply apply=response.body();
                Utiltools.printE("tag创建申请的返回的",JSON.toJSONString(apply)+"===");
                if(TextUtils.isEmpty(apply.getError())){
                    if(callback!=null){
                        callback.success(apply);
                    }
                }else{
                    MessageBox.ToastShow(apply.getError()+"",context);
                    return;
                }
            }

            @Override
            public void onFailure(Call<Apply> call, Throwable t) {

            }
        });
    }

    /**
     * 获取最新的申请
     * @param callback
     */
    public void latesApplication(final GetApplyCallback  callback){
        latesApplication=retrofit.create(Service.latesApplication.class);
        Call<Apply> resp=latesApplication.attemlatesApplication(LocalCache.getStringLocalData(context,"objectId"),
                LocalCache.getStringLocalData(context,"accessToken"),LocalCache.getStringLocalData(context,"applicationId"));
        resp.enqueue(new Callback<Apply>() {
            @Override
            public void onResponse(Call<Apply> call, Response<Apply> response) {
                Apply applyInfo=response.body();
                if(TextUtils.isEmpty(applyInfo.getError())){
                    if(callback!=null){
                        Utiltools.printE("获取最新的申请",JSON.toJSONString(applyInfo)+"===");
                        LocalCache.saveDataToLocal(context,"creditId",applyInfo.getCreditId());//保存creditId到缓存
                        LocalCache.saveDataToLocal(context,"isEnabled",applyInfo.getIsEnabled()+"");//保存isEnabled到缓存
                        Timber.e("asdsad");
                   /*     Apply apply=new Apply();
                        apply.setAmountRequested(applyInfo.getAmountRequested());
                        apply.setAppStatus(applyInfo.getAppStatus());
                        apply.setCashadvanceId(applyInfo.getCashadvanceId());
                        apply.setCashadvanceStatus(applyInfo.getCashadvanceStatus());
                        apply.setCoupons(applyInfo.getCoupons());
                        apply.setCreatedAt(applyInfo.getCreatedAt());
                        apply.setCreditId(applyInfo.getCreditId());
                        apply.setCreditReportStatus(applyInfo.getCreditReportStatus());
                        apply.setFamilyInfoCompleted(applyInfo.getFamilyInfoCompleted());
                        apply.setIdentificationCompleted(applyInfo.getIdentificationCompleted());
                        apply.setIsAmountLocked(applyInfo.getIsAmountLocked());
                        apply.setIsDocumentLocked(applyInfo.getIsDocumentLocked());
                        apply.setIsJxlValid(applyInfo.getIsJxlValid());
                        apply.setIsSubmitApplication(applyInfo.getIsSubmitApplication());
                        apply.setLeadStatus(applyInfo.getLeadStatus());
                        apply.setLeaseInfoCompleted(applyInfo.getLeaseInfoCompleted());
                        apply.setObjectId(applyInfo.getObjectId());
                        apply.setStatus(applyInfo.getStatus());
                        apply.setStatusDetail(applyInfo.getStatusDetail());
                        apply.setStoreInfoCompleted(applyInfo.getStoreInfoCompleted());
                        apply.setUpdatedAt(applyInfo.getUpdatedAt());
                        apply.setVerifyVideoStatus(applyInfo.getVerifyVideoStatus());
                        apply.setIsEnabled(applyInfo.getIsEnabled());*/
                        // apply.set     "loaded": true,
                        // apply.set         "valid": false,
                        realm.beginTransaction();
                        realm.copyToRealmOrUpdate(applyInfo);
                        realm.commitTransaction();

                        callback.success(applyInfo);
                    }
                }else{
                    MessageBox.ToastShow(applyInfo.getError()+"",context);
                    return;
                }
            }

            @Override
            public void onFailure(Call<Apply> call, Throwable t) {

            }
        });
    }


    /**
     * 获取授信
     * @param creditId
     */
    public  void getCreditLimitService(final String creditId, final GetCreditCallback  callback){
        Utiltools.printE("获取授信的状态=11111===","=====UserService  creditId"+creditId+"creditId");
        getCreditLimitService=retrofit.create(Service.getCreditLimit.class);
        Call<Credit>   resp=getCreditLimitService.attemGetCreditLimit(LocalCache.getStringLocalData(context,"objectId"),
                LocalCache.getStringLocalData(context,"accessToken"),creditId);
        resp.enqueue(new Callback<Credit>() {
            @Override
            public void onResponse(Call<Credit> call, Response<Credit> response) {
                Utiltools.printE("获取授信的状态=22===",response.body().toString() +"=====UserService");
                Credit creditLimit=response.body();
                if (creditLimit == null) {
                    Utiltools.printE("TSGSSS", "kongkongkong");
                    return;
                }else{
                    String  error= creditLimit.getError()+"";
                    Utiltools.printE("获取授信的Error",error+"---"+JSON.toJSONString(creditLimit).toString());

                    if(error.equals("null")){
                        if(callback!= null){
                            Utiltools.printE("2016-6-12",creditLimit.getCreditStatus()+"=======");
                            if(creditLimit.getCreditStatus()!=null&&!creditLimit.getCreditStatus().equals("")){
                                LocalCache.saveDataToLocal(context,"creditStatus",creditLimit.getCreditStatus().toString());
                                LocalCache.getStringLocalData(context,"creditStatus");
                           /* Credit credit=new Credit();
                            credit.setPaymentMethod(creditLimit.getPaymentMethod());
                            credit.setCreditStatus(creditLimit.getCreditStatus());
                            credit.setLoanPeriod(creditLimit.getLoanPeriod());
                            credit.setPaymentMethodId(creditLimit.getPaymentMethodId());
                            credit.setTotalCreditLine(creditLimit.getTotalCreditLine());
                            credit.setLastUpdateTime(creditLimit.getLastUpdateTime());
                            credit.setInvalidDate(creditLimit.getInvalidDate());
                            credit.setObjectId(creditLimit.getObjectId());*/
                                realm.beginTransaction();
                                realm.copyToRealmOrUpdate(creditLimit);
                                Utiltools.printE("获取授信的55555",error+"---"+JSON.toJSONString(creditLimit));
                                realm.commitTransaction();
                                Credit results1 =realm.where(Credit.class).equalTo("creditStatus",LocalCache.getStringLocalData(context,"creditStatus")).findFirst();
                                Utiltools.printE("设置获取授信成功时，参考额度里面的值","==="+ JSON.toJSONString(results1));

                            }
                            callback.success(creditLimit);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<Credit> call, Throwable t) {

            }
        });

    }

    /**
     * 创建授信
     * 传入  applicationId，是json的类型
     * @param callback
     */
    public void getCreditLimit(final CreditLimitCallback callback){
        creditLimitService=retrofit.create(Service.CreateCreditLimit.class);
        Credit credit=new Credit();
        credit.setApplicationId(Integer.parseInt(LocalCache.getStringLocalData(context,"applicationId")));
        Call<Credit>  resp= creditLimitService.attemCredit(LocalCache.getStringLocalData(context,"objectId"),
                LocalCache.getStringLocalData(context,"accessToken"),credit);
        resp.enqueue(new Callback<Credit>() {
            @Override
            public void onResponse(Call<Credit> call, Response<Credit> response) {
                Credit  creditLimit=response.body();
                String Error=creditLimit.getError()+"";
                Utiltools.printE("创建授信",  creditLimit.getObjectId()+"----"+creditLimit.getCode()+"===code+++"+creditLimit.getError()+"===");
                if(Error.equals("null")){
                    if(callback!=null){
                        LocalCache.saveDataToLocal(context,"creditId",creditLimit.getObjectId());
                        callback.success(creditLimit);
                    }
                }else{
                    MessageBox.ToastShow(Error,context);
                    return;
                }
            }

            @Override
            public void onFailure(Call<Credit> call, Throwable t) {

            }
        });
    }


    /**
     * 查询行业清单1
     */
    public void getIndustrylist(String industryGId, String industryPId,final IndustryCallback callback){
        //第一次调用的话，一些这几个参数都为null
        if(industryPId!=null){
            industryGId=industryPId;
        }
        industrylistService=retrofit.create(Service.industrylist.class);
        Call<ArrayList<Industrylist>> resp=industrylistService.attemIndustrylist(
                LocalCache.getStringLocalData(context,"objectId"),
                LocalCache.getStringLocalData(context,"accessToken"),industryGId);
        resp.enqueue(new Callback<ArrayList<Industrylist>>() {
            @Override
            public void onResponse(Call<ArrayList<Industrylist>> call, Response<ArrayList<Industrylist>> response) {
                ArrayList<Industrylist> industrylists=response.body();
                if(callback!=null){
                    callback.success(industrylists);
                }
            }

            @Override
            public void onFailure(Call<ArrayList<Industrylist>> call, Throwable t) {

            }
        });
    }


    public  interface IndustryCallback{
        void success( ArrayList<Industrylist> industrylists);

        void fail(String msg);

        void cancelDialog();
    }


    /**
     * 获取融资期限的列表
     */
    public void getPlanFundTerm(final PlanFundTermCallback callback){
        getPlanFundTermService=retrofit.create(Service.getPlanFundTerm.class);
        Utiltools.printE("tag-t",LocalCache.getStringLocalData(context,"accessToken"));
        Utiltools.printE("tag-o",LocalCache.getStringLocalData(context,"objectId"));
        Call<ArrayList<SelHasLeaseContract>> resp=getPlanFundTermService.attemPlanFundTerm(
                LocalCache.getStringLocalData(context,"objectId"),LocalCache.getStringLocalData(context,"accessToken"));
        resp.enqueue(new Callback<ArrayList<SelHasLeaseContract>>() {
            @Override
            public void onResponse(Call<ArrayList<SelHasLeaseContract>> call, Response<ArrayList<SelHasLeaseContract>> response) {
                ArrayList<SelHasLeaseContract> planFundTerm=response.body();
                if(callback!=null){
                    callback.success(planFundTerm);
                }
            }

            @Override
            public void onFailure(Call<ArrayList<SelHasLeaseContract>> call, Throwable t) {

            }
        });
    }

    public  interface  PlanFundTermCallback {
        void success( ArrayList<SelHasLeaseContract> planFundTerm);

        void fail(String msg);

        void cancelDialog();
    }
    /**
     * 获取用户
     * @param userId
     */
    public  void   getGetUserInfo(String userId,final UsesrCallback callback){
        getUserInfoService=retrofit.create(Service.getUserInfo.class) ;
        Call<User> repos=getUserInfoService.attempGetUserInfo(LocalCache.getStringLocalData(context,"objectId"),
                LocalCache.getStringLocalData(context,"accessToken"),userId);
        repos.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                User userInfo=response.body();
                Utiltools.printE("获取用户",JSON.toJSONString(userInfo).toString());
                if(TextUtils.isEmpty(userInfo.getError())){

                    if (callback != null) {
                     /*   RealmResults<User> results = realm.where(User.class).findAll();
                        realm.beginTransaction();
                        results.deleteAllFromRealm();
                        realm.commitTransaction();*/
                        LocalCache.saveDataToLocal(context,"mobilePhone",userInfo.getMobilePhone());
                       /* User user =new User();
                        user.setMobilePhone(userInfo.getMobilePhone());
                        user.setProvinceId(userInfo.getProvinceId());//所属省份
                        user.setBizRegisterNo(userInfo.getBizRegisterNo());//营业注册号
                        user.setIndustryGId(userInfo.getIndustryGId());//所属行业(一级)
                        user.setIndustryPId(userInfo.getIndustryPId());//所属行业(二级)
                        user.setIndustryCId(userInfo.getIndustryCId());//所属行业(三级)
                        user.setIndustryGId(userInfo.getIndustryGName());//所属行业(一级title)
                        user.setIndustryPId(userInfo.getIndustryPName());//所属行业(二级title)
                        user.setIndustryCId(userInfo.getIndustryCName());//所属行业(三级title)

                        user.setCityId(userInfo.getCityId());//所属城市
                        user.setLoanAmount(userInfo.getLoanAmount());//拟融资金额
                        user.setIsJxlValid(userInfo.getIsJxlValid());//手机验证
                        user.setBusinessAddress(userInfo.getBusinessAddress());//营业地址
                        user.setCorporateName(userInfo.getCorporateName());//企业名称
                        user.setBusinessName(userInfo.getBusinessName());//经营名称
                        user.setBizAddrLonlat(userInfo.getBizAddrLonlat());//经纬度
                        user.setLandlordPhone(userInfo.getLandlordPhone());//手机号码
                        user.setEmergencyName(userInfo.getEmergencyName());//紧急联系人
                        user.setEmergencyPhone(userInfo.getEmergencyPhone());//紧急联系人手机号
                        user.setDirectName(userInfo.getDirectName());//直系亲属姓名
                        user.setDirectType(userInfo.getDirectType());//直系亲属类型
                        user.setDirectPhone(userInfo.getDirectPhone());//直系亲属手机号
                        user.setSecondaryBankDDA(userInfo.getSecondaryBankDDA());//放款账户号
                        user.setSecondaryBankName(userInfo.getSecondaryBankName());//放款账户银行
                        user.setHasLeaseContract(userInfo.getHasLeaseContract());//是否有租赁合同
                        user.setNoLeaseContractReason(userInfo.getNoLeaseContractReason());//无租赁合同原因
                        user.setProposerName(userInfo.getProposerName());//业主
                        user.setProprietorPhone(userInfo.getProprietorPhone());//号码
                        user.setLeaseContractStartTime(userInfo.getLeaseContractStartTime());//开始时间
                        user.setLeaseContractEndTime(userInfo.getLeaseContractEndTime());//结束时间
                        user.setLeaseYearAmt(userInfo.getLeaseYearAmt());//金额
                        user.setNumLocations(userInfo.getNumLocations());//门店数
                        user.setYearTurnover(userInfo.getYearTurnover());//年营业额
                        user.setPlanFundTerm(userInfo.getPlanFundTerm());//拟融资期限月数
                        user.setCouponIds(userInfo.getCouponIds());//红包的id
                        user.setCouponIds(userInfo.getPlanFundTermName());//融资期限的title
*/

                        realm.beginTransaction();
                        // User user2 = realm.copyToRealm(userInfo);
                        realm.copyToRealmOrUpdate(userInfo);
                        realm.commitTransaction();
                        callback.success(userInfo);
                    }
                }
            }


            @Override
            public void onFailure(Call<User> call, Throwable t) {

            }
        });

    }

    /**
     * <P>更新用户</P>
     * @param user
     * @param callback
     */
    public  void  updateInfo(User user,final UsesrCallback callback){
        // User user=new User();
       /* user.setProvinceId("");//所属省份
        user.setBizRegisterNo("");//营业注册号
        user.setIndustryGId("");//所属行业(一级)
        user.setIndustryPId("");//所属行业(二级)
        user.setIndustryCId("");//所属行业(三级)
        user.setCityId("");//所属城市
        user.setLoanAmount("");//拟融资金额
        user.setIsJxlValid("");//手机验证
        user.setBusinessAddress("");//营业地址
        user.setCorporateName("");//企业名称
        user.setBusinessName("");//经营名称
        user.setBizAddrLonlat("121.1231321312,123.12311231");//经纬度
        user.setLandlordPhone("");//手机号码
        user.setEmergencyName("");//紧急联系人
        user.setEmergencyPhone("");//紧急联系人手机号
        user.setDirectName("");//直系亲属姓名
        user.setDirectType("");//直系亲属类型
        user.setDirectPhone("");//直系亲属手机号
        user.setSecondaryBankDDA("");//放款账户号
        user.setSecondaryBankName("");//放款账户银行
        user.setHasLeaseContract("");//是否有租赁合同
        user.setNoLeaseContractReason("");//无租赁合同原因
        user.setProposerName("");//业主
        user.setProprietorPhone("");//号码
        user.setLeaseContractStartTime("");//开始时间
        user.setLeaseContractEndTime("");//结束时间
        user.setLeaseYearAmt("");//金额
        user.setNumLocations("");//门店数
        user.setYearTurnover("");//年营业额
        user.setPlanFundTerm("");//拟融资期限月数
        user.setCouponIds("");//红包的id
        String blackBox = FMAgent.onEvent();
        user.setBlackBox(blackBox);//同盾*/
        updateInfoService=retrofit.create(Service.UpdateInfo.class) ;
        Call<User>  repos= updateInfoService.attempUpdateInfo(
                LocalCache.getStringLocalData(context,"objectId"),
                LocalCache.getStringLocalData(context,"accessToken"),
                LocalCache.getStringLocalData(context,"objectId"),user);
        repos.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                User user=response.body();
                Utiltools.printE("=====",user.getError()+"==="+user.getUpdatedAt()+"---");
                String error=user.getError()+"";
                if(error.equals("null")){
                    if (callback != null) {
                        callback.success(user);
                    }
                }

                if(!error.equals("null")){
                    if (callback != null) {
                        callback.cancelDialog();
                    }
                    MessageBox.ToastShow(user.getError()+"",context);
                    return;
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {

            }
        });
    }



    public  interface  UsesrCallback {
        void success(User userInfo);

        void fail(String msg);

        void cancelDialog();
    }


    /**
     * 创建授信的接口
     */

    public  interface  CreditLimitCallback{
        void success( Credit  creditLimit);

        void fail(String msg);

        void cancelDialog();
    }


    /**
     * 获取授信的接口
     */
    public  interface  GetCreditCallback{
        void success( Credit  creditLimit);

        void fail(String msg);

        void cancelDialog();
    }


    /**
     * 获取最新的申请的接口
     */
    public  interface  GetApplyCallback{
        void success(Apply apply);

        void fail(String msg);

        void cancelDialog();
    }


    /**
     * 获取消息
     */
    public  interface  GetMessageCallback{
        void success(ArrayList<Message> message);

        void fail(String msg);

        void cancelDialog();
    }


    /**
     * 获取图片
     */
    public  interface  GetFileListOnceCallback{
        void success(FileListOnce fileListOnce);

        void fail(String fileListOnce);

        void cancelDialog();
    }


    /**
     * 聚信力第一步   第二步
     * jxlGetVerityCode
     */
    public  interface  GetjxlGetVerityCodeCallback{
        void success(User user);

        void fail(User user);

        void cancelDialog();
    }


    /**
     *征信报告的验证码 VerifyImgCode   和第二步
     */
    public  interface  GetcreatVerityCodeCallback{
        void success(VerifyImgCode verifyImgCode);

        void fail(VerifyImgCode verifyImgCode);

        void cancelDialog();
    }


    /**
     *融资保理
     */
    public  interface  GetConfirmlistCallback{
        void success( ArrayList<Confirmlist> confirmlist);

        void fail( ArrayList<Confirmlist> confirmlist);

        void cancelDialog();
    }


    /**
     * 授权
     */
    public interface  GetPostCreateAuthCallback{
        void success(PostCreateAuth task);

        void fail(PostCreateAuth task);

        void cancelDialog();
    }

    /**
     *查询银行清单
     */
    public interface  GetBankCallback{
        void success(Bank bank);

        void fail(Bank bank);

        void cancelDialog();
    }
}
